/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.serviceapp.service.branchstores.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.BranchWarehouse;
import com.qinyeit.serviceapp.entity.MaterialCostDetail;
import com.qinyeit.serviceapp.entity.Warehouse;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.service.branchstores.BranchWarehouseService;
import com.qinyeit.serviceapp.service.branchstores.MaterialCostDetailService;
import com.qinyeit.serviceapp.service.stores.WarehouseService;
import com.qinyeit.serviceapp.utils.LocalUtils;
import com.qinyeit.serviceapp.utils.SearchUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.lang.StringUtils;
import com.qinyetech.springstage.core.repository.jdbc.PageNamedParameterJdbcTemplate;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.qinyetech.springstage.core.service.BaseService;
import com.qinyeit.serviceapp.entity.MaterialCost;
import com.qinyeit.serviceapp.repository.branchstores.MaterialCostRepository;
import com.qinyeit.serviceapp.service.branchstores.MaterialCostService;

import java.util.List;
import java.util.Map;

/** 
 * ClassName: MaterialCostServiceImpl <br/> 
 * Function: 成本卡 业务实现 <br/> 
 * date: 2018-12-01 14:09:56 <br/> 
 * 
 * @author liuwenjin
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@Transactional
public class MaterialCostServiceImpl extends BaseService<MaterialCost, Long> implements MaterialCostService {


	@Autowired
	private MaterialCostRepository materialCostRepository;
	@Autowired
	private PageNamedParameterJdbcTemplate jdbcTemplate;
//	@Autowired
//	private WarehouseService warehouseService;
	@Autowired
	private BranchWarehouseService branchWarehouseService;
	@Autowired
	private MaterialCostDetailService materialCostDetailService;


	@Override
	public Page<Map<String,Object>> findAllForDishes(Searchable searchable,Long merchantGroupId) {

		String sql = "SELECT r.def, r.dishes_id, r.price, r.spec_id, r.spec_name\n" +
				"\t, r.store_id, r.vip_price, d.name AS dishes_name, d.price AS dishes_price, d.vip_price AS dishes_vip_price\n" +
				"\t, d.name_en AS dishes_name_en, d.pinyin AS dishes_pinyin, d.no AS dishes_no, k.name AS store_name, c.id AS mcId\n" +
				"\t, IFNULL(c.cost, 0) AS cost\n" +
				"FROM dishes_specification_relations r\n" +
				"\tLEFT JOIN dishess d ON d.id = r.dishes_id\n" +
				"\tLEFT JOIN dishes_specifications s ON s.id = r.spec_id\n" +
				"\tLEFT JOIN dishes_stores k ON k.id = r.store_id\n" +
				"\tLEFT JOIN material_costs c ON c.dishes_id = d.id AND ((r.spec_id IS NULL AND c.spec_id IS NULL) OR r.spec_id=c.spec_id) \n" +
				"WHERE d.merchant_group_id = :merchantGroupId\n" +
				"\tAND d.is_deleted = 0\n" +
				"\tAND d.type = 'DISHES'\n" ;

		QyMap map = QyMap.map("merchantGroupId",merchantGroupId);

		String storeId = searchable.getValue("storeId_eq");
		if(StringUtils.isNotBlank(storeId)){
			sql += " and  k.id = :storeId";
			map.setv("storeId",storeId);
		}
		//菜品名称或编码
		String dName = searchable.getValue("dName_eq");

		//原材料名称
		String mName = searchable.getValue("mName_eq");
		if(StringUtils.isNotBlank(dName)){
			sql += " AND (d.no LIKE :dname OR d.name LIKE :dname)";
			map.setv("dname","%"+dName+"%");
		}
		if(StringUtils.isNotBlank(mName)){
			sql += " AND c.id IN ( " +
					" SELECT mc.id " +
					" FROM material_cost_details mcd " +
					"  LEFT JOIN material_costs mc ON mc.id = mcd.cost_id " +
					"  LEFT JOIN materials m ON m.id = mcd.material_id " +
					" WHERE m.name LIKE :mname " +
					" GROUP BY mc.id " +
					" )";
			map.setv("mname","%"+mName+"%");
		}

		Page<Map<String,Object>> list = jdbcTemplate.queryForList(sql,map,searchable.getPage());


		return list;
	}

	@Override
	public Object findDishOne(Long specId, Long dishesId,Long merchantGroupId,Long storeId) {

		String sql=" SELECT  " +
				" d.id, d.name, ds.name AS specName FROM dishes_specification_relations dsr "+
				" LEFT JOIN dishess d ON d.id=dsr.dishes_id "+
				" LEFT JOIN dishes_specifications ds ON ds.id=dsr.spec_id "+
				" WHERE d.id=:dishesId and d.merchant_group_id=:merchantGroupId and dsr.store_id = :storeId";
		QyMap map = QyMap.map("merchantGroupId",merchantGroupId)
				.setv("dishesId",dishesId)
				.setv("storeId",storeId);
		if(specId!=0){
			sql+="  AND ds.id=:specId";
			map.setv("specId",specId);
		}

		Map<String, Object> findOne=jdbcTemplate.queryForMap(sql,map);
		return findOne;
	}

	@Override
	public void saveData(JSONObject data, Long merchantGroupId) {

		JSONObject object= data.getJSONObject("modelForm");


		Long storageId = object.getLong("warehouseId");
		BranchWarehouse storage = branchWarehouseService.findById(storageId);
	/*	if(storage==null){
			throw new BusinessRunTimeException("仓库不存在", 1001);
		}*/
		JSONArray array=data.getJSONArray("items");
		if(array==null || array.size()==0){
			throw new BusinessRunTimeException("请选择原料", 1003);
		}
		Searchable searchable = SearchUtils.newSearchableWithMerchantFilter(merchantGroupId);
		searchable.addSearchParam("storeId_eq",object.getLong("storeId"));
		searchable.addSearchParam("dishesId_eq",object.getLong("dishesId"));
		searchable.addSearchParam("specId_eq",object.getLong("specId"));
		MaterialCost materialCost = super.findOne(searchable);

		log.info("materialCost : {}",materialCost);
		log.info("dishesId : {}",object.getLong("dishesId"));

		if(materialCost==null){
			materialCost =new MaterialCost();
			materialCost.setUuid(LocalUtils.getUUID());
			materialCost.setUpdateTimestamp(DateUtils.current());
			materialCost.setSpecId(object.getLong("specId"));
			materialCost.setDishesId(object.getLong("dishesId"));
			materialCost.setStoreId(object.getLong("storeId"));

		}else{
			materialCost.setUpdateTimestamp(DateUtils.current());
			materialCostRepository.deleteByCostId(materialCost.getId());
		}
		materialCost.setStoreId(object.getLong("storeId"));
		materialCost.setMerchantGroupId(merchantGroupId);
		materialCost.setWarehouseId(storageId);
		materialCost.setRemark(object.getString("remark"));
		materialCost.setCost(object.getDouble("cost"));
		materialCost.setMaterialCost(object.getDouble("materialCost"));
		materialCost.setOtherCost(object.getDouble("otherCost"));
		materialCost.setProcessQty(object.getInteger("processQty"));
		this.save(materialCost);
		JSONArray items= data.getJSONArray("items");
		if(items==null || items.size()==0){
			throw new BusinessRunTimeException("请选择订单内的商品", 1003);
		}
		JSONObject item ;
		MaterialCostDetail detail;
		for(int i=0;i<items.size();i++) {
			item = items.getJSONObject(i);
			detail=new MaterialCostDetail();
			detail.setRemark(item.getString("memo"));
			detail.setCost(materialCost);
			detail.setMaterialId(item.getLong("id"));
			detail.setExpend(item.getDouble("count"));
			detail.setMerchantGroupId(merchantGroupId);
			detail.setPrincipal(item.getBoolean("isMain"));
			materialCostDetailService.save(detail);
		}

	}
	@Transactional
	public void deleteDetails(Long id){
		materialCostRepository.deleteByCostId(id);
	}
}